﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using System.Collections.Generic;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxPlanProgressController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxPlanProgressController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        /// <summary>
        /// 办结反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_PlanProgress model)
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;
            var IsJb = false;
            string headtitle = "", text = "";
            string AccountId = "";
            if (SuperviseID > 0)
            {
                var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = "领导督导";
                    var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                    AccountId = user.AccountId.ToString();
                }
            }
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
                var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == ItemID);
                if (c != null)
                {
                    headtitle = "领导协调";
                    text = "协调内容  " + c.Item;
                }
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
                var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = "精准督查";
                    var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                    AccountId = user.AccountId.ToString();
                }
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
                var s = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = s.TaskType.ToString();
                    var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                    AccountId = user.AccountId.ToString();
                }
                IsJb = true;
            }
            switch (ItemType)
            {
                case 事项类型.钉办督导:
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                    if (s != null && s.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.协同管理:
                    var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CooperativeID == CoordinateID);
                    if (r != null && r.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.精准督查:
                    var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == eSuperviseID);
                    if (e != null && e.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.专项交办:
                    var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == sSuperviseID);
                    if (rs != null && rs.IsFinish)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0,
                            msg = "任务已归档"
                        });
                    }
                    if (rs != null && rs.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
            }

            model.ItemID = ItemID;
            model.ItemType = ItemType;
            model.CheckStatus = 审核状态.待审;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_PlanProgress.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                var TaskName = "";
                var tID = model.TaskID;
                if (ItemType == 事项类型.专项交办)
                {
                    tID = 0;
                    var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == model.TaskID);
                    if (t != null) TaskName = t.Name;
                }
                else
                {
                    var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == model.TaskID);
                    if (task != null) TaskName = task.TaskName;
                }
                var TaskID = IsJb ? ItemID : model.TaskID;
                var plan = ctx.Yqd_JobPlan.FirstOrDefault(it => it.PlanID == model.PlanID);
                var cnt = "";
                if (plan != null) cnt = "反馈了工作计划(" + plan?.Measure + ")" + model.FeedbackTime.ToString("yyyy-MM-dd") + "期进展情况";
                //关闭通知
                var msg = ddService.Notification(new List<string>() { AccountId }, headtitle, tID.ToString(), "任务名称:" + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})反馈了进展情况，请及时审核！", true, pushStep: 推送流程.工作流转, unitCode: WxUser.LogonInfo.UnitCode);
                Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了进展情况通知，返回值：" + msg);
                TaskLogService.AddLog(TaskID, cnt, IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var l = WxUser.LogonInfo;
            if (!l.Role.Contains(角色类型.管理员))
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "无权限删除"
                });
            }
            var ProgressID = Form.GetInt("ProgressID");
            var s = ctx.Yqd_PlanProgress.FirstOrDefault(it => it.ProgressID == ProgressID);
            var ret = ctx.Database.ExecuteSql("update Yqd_PlanProgress set IsDel=1 where ProgressID={0};", ProgressID);
            if (ret > 0)
            {
                var IsJb = s.ItemType == 事项类型.专项交办;
                var TaskID = IsJb ? s.ItemID : s.TaskID;
                TaskLogService.AddLog(TaskID, "删除了进展反馈(" + s.ProgressInfo + "", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret,
                msg = "删除成功"
            });
        }

        /// <summary>
        /// 审核进展反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [User]
        public IActionResult Check()
        {
            var ProgressID = Form.GetInt("ProgressID");
            var m = ctx.Yqd_PlanProgress.FirstOrDefault(it => it.ProgressID == ProgressID);
            var ret = 0;
            if (m != null)
            {
                var auditList = ctx.Yqd_PlanProgress.Where(x => x.PlanID == m.PlanID && x.AuditStatus == 0 && m.ProgressStatus != 任务状态.已完成).ToList();
                foreach (var item in auditList)
                {
                    item.AuditStatus = 1;
                    ctx.SaveChanges();
                }

                m.ProgressStatus = (任务状态)Form.GetInt("Status");
                m.CheckStatus = (审核状态)Form.GetInt("CheckStatus");
                m.ReturnReason = Form.GetString("Reason");
                m.CheckTime = DateTime.Now;
                //if (m.ProgressStatus != 任务状态.已完成)
                //{
                m.AuditStatus = 1;
                //}


                ret = ctx.SaveChanges();
                if (ret > 0)
                {
                    var plan = ctx.Yqd_JobPlan.FirstOrDefault(it => it.PlanID == m.PlanID);
                    if (m.CheckStatus == 审核状态.同意)
                    {
                        var sql = "update Yqd_JobPlan set ";
                        var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == m.AssignID);
                        if (a != null)
                        {
                            var TimeLine = "";
                            if (m.ProgressStatus == 任务状态.已完成)
                            {
                                sql += " PlanStatus=" + (int)工作计划状态.已完成 + " where PlanID=" + plan.PlanID;
                                var ps = ctx.Yqd_JobPlan.Where(it => it.PlanID != plan.PlanID && it.SchemeID == m.SchemeID).OrderBy(x => x.CompleteTime).ThenBy(it => it.PlanID).ToList();
                                var pl = ps.FirstOrDefault(it => it.CompleteTime >= plan.CompleteTime);
                                if (pl != null)
                                {
                                    //下个月反馈，更新反馈时间
                                    if (a.FeedbackLoop == 进展反馈周期.每月25日 || a.FeedbackLoop == 进展反馈周期.每月28日)
                                    {
                                        TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, m.CheckTime.Value, DateTime.Now.AddMonths(1), a.Days);
                                    }
                                    else
                                    {
                                        TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, m.Instime, plan.CompleteTime, a.Days);
                                        //完成时间相同时，同时提醒
                                        var ll = ctx.Yqd_JobPlan.Where(it => it.PlanID != plan.PlanID && it.SchemeID == m.SchemeID && it.CompleteTime == pl.CompleteTime).ToList();
                                        if (ll.Any() && ll.Count > 1)
                                        {
                                            foreach (var item in ll)
                                            {
                                                sql += ";update Yqd_JobPlan set TimeLine='" + TimeLine + "' where PlanID=" + item.PlanID;
                                            }
                                        }
                                    }
                                    sql += ";update Yqd_JobPlan set TimeLine='" + TimeLine + "' where PlanID=" + pl.PlanID;
                                }
                            }
                            else
                            {
                                TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, m.FeedbackTime.Value, plan.CompleteTime, a.Days);
                                sql += " TimeLine=TimeLine+','+" + TimeLine + " where PlanID=" + plan.PlanID;
                            }
                            var result = ctx.Database.ExecuteSql(sql);

                            Logs.Information<SuperviseHostService>($"更新工作计划状态Yqd_JobPlan：{sql},结果：{result}");

                        }
                        var scheme = ctx.Yqd_Scheme.Where(x => x.CheckStatus != 审核状态.退回 && x.ItemID == plan.ItemID && x.AssignID == plan.AssignID).Select(x => x.SchemeID).ToList();

                        var PCount = ctx.Yqd_JobPlan.Count(it => scheme.Any(x => x == it.SchemeID) && it.ItemID == plan.ItemID && it.ItemType == plan.ItemType && it.PlanStatus != 工作计划状态.已完成);
                        if (PCount == 0)
                        {
                            SuperviseService.UpdateComplete(plan.ItemID, plan.ItemType);
                        }
                        else
                        {
                            任务状态 ProgressStatus = 任务状态.正常推进;
                            var lastList = ctx.Yqd_PlanProgress.Where(x => x.ItemID == plan.ItemID && x.PlanID != m.PlanID && x.CheckTime != null).GroupBy(x => x.PlanID).Select(x => new
                            {
                                planId = x.Key,
                                listP = x.OrderByDescending(y => y.Instime).Take(1).ToList()
                            }).ToList();
                            if (lastList.Any())
                            {
                                if (lastList.SelectMany(x => x.listP).Any(x => x.ProgressStatus == 任务状态.滞后))
                                {
                                    ProgressStatus = 任务状态.滞后;
                                }
                            }
                            SuperviseService.UpdateComplete(plan.ItemID, plan.ItemType, ProgressStatus);
                        }
                    }
                    else
                    {
                        if (m.ProgressStatus != 任务状态.退回)
                        {
                            任务状态 ProgressStatus = 任务状态.正常推进;
                            var lastList = ctx.Yqd_PlanProgress.Where(x => x.ItemID == plan.ItemID && x.PlanID != m.PlanID && x.CheckTime != null).GroupBy(x => x.PlanID).Select(x => new
                            {
                                planId = x.Key,
                                listP = x.OrderByDescending(y => y.Instime).Take(1).ToList()
                            }).ToList();
                            if (lastList.Any())
                            {
                                if (lastList.SelectMany(x => x.listP).Any(x => x.ProgressStatus == 任务状态.滞后))
                                {
                                    ProgressStatus = 任务状态.滞后;
                                }
                                else
                                {
                                    //选最严重状态
                                    if (m.ProgressStatus > ProgressStatus)
                                    {
                                        ProgressStatus = m.ProgressStatus;
                                    }
                                }
                            }
                            else
                            {
                                ProgressStatus = m.ProgressStatus;
                            }
                            SuperviseService.UpdateComplete(plan.ItemID, plan.ItemType, ProgressStatus);
                        }
                    }
                    string headtitle = "", text = "";
                    var IsJb = false;
                    List<string> accountId = new List<string>();
                    string employeeName = "";
                    switch (m.ItemType)
                    {
                        case 事项类型.钉办督导:
                            var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (s != null)
                            {
                                headtitle = "领导督导";
                                var approval = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && it.ItemType == 事项类型.钉办督导).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
                                if (approval != null)
                                {
                                    employeeName = approval.DeptLeader;
                                }
                            }
                            break;
                        case 事项类型.协同管理:
                            var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == m.ItemID);
                            if (c != null)
                            {
                                headtitle = "领导协调";
                                text = "协调内容  " + c.Item;
                            }
                            break;
                        case 事项类型.精准督查:
                            var es = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (es != null)
                            {
                                headtitle = "精准督查";
                                var approval = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && it.ItemType == 事项类型.精准督查).OrderByDescending(x => x.ApprovalID).FirstOrDefault();

                                if (approval != null)
                                {
                                    employeeName = approval.DeptLeader;
                                }
                            }
                            break;
                        case 事项类型.专项交办:
                            var ss = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (ss != null)
                            {
                                headtitle = ss.TaskType.ToString();
                                var approval = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && (it.ItemType == 事项类型.专项交办 || it.ItemType == 事项类型.专项督查)).OrderByDescending(x => x.ApprovalID).FirstOrDefault();

                                if (approval != null)
                                {
                                    employeeName = approval.DeptLeader;
                                }
                            }
                            IsJb = true;
                            break;
                    }
                    var TaskName = "";
                    var tID = m.TaskID;
                    if (m.ItemType == 事项类型.专项交办)
                    {
                        tID = 0;
                        var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == m.TaskID);
                        if (t != null) TaskName = t.Name;
                    }
                    else
                    {
                        var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == m.TaskID);
                        if (task != null) TaskName = task.TaskName;
                    }
                    var l = WxUser.LogonInfo;
                    var assign = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == m.AssignID);
                    //关闭通知
                    if (m.CheckStatus == 审核状态.退回)
                    {
                        var msg = ddService.Notification(accountId, headtitle, tID.ToString(), "任务名称: " + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})退回了进展反馈，请重新报送！", pushStep: 推送流程.工作退回, unitCode: assign.LeadUnit, employeeNames: new List<string>() { employeeName });
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了退回进展反馈通知，返回值：" + msg);
                    }
                    TaskLogService.AddLog(IsJb ? m.ItemID : m.TaskID, (m.AuditStatus == 1 ? "审核" : m.CheckStatus.ToString()) + "了工作计划(" + plan?.Measure + m.ProgressStatus + ")进展情况(" + m.ProgressInfo + ")", IsJb);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult GetHistory()
        {
            var PlanID = Form.GetInt("PlanID");
            var data = ctx.Database.SqlQuery<Yqd_PlanProgress>("select * from Yqd_PlanProgress where [PlanID]={0} and [CheckStatus]={1} order by [Instime] desc", PlanID, (int)审核状态.退回);
            return this.ToJson(new
            {
                success = true,
                totalcount = data.Count(),
                data = data.ToList().Select(it => new
                {
                    it.ProgressID,
                    FeedbackTime = it.FeedbackTime.ToString("yyyy-MM-dd"),
                    ProgressStatus = it.ProgressStatus.ToString(),
                    it.ProgressInfo,
                    it.ProofMaterial,
                    it.Experience,
                    it.ExperienceMaterial,
                    it.ReturnReason
                })
            });
        }

        [User]
        public ActionResult Repeal()
        {
            var ProgressID = Form.GetInt("ProgressID");
            var ret = ctx.Database.ExecuteSql("update Yqd_PlanProgress set CheckStatus={1},ReturnReason=null,CheckTime=null where ProgressID={0}", ProgressID, (int)审核状态.待审);
            if (ret > 0)
            {
                var p = ctx.Yqd_PlanProgress.FirstOrDefault(it => it.ProgressID == ProgressID);
                var IsJb = p.ItemType == 事项类型.专项交办;
                var plan = ctx.Yqd_JobPlan.FirstOrDefault(it => it.PlanID == p.PlanID);
                TaskLogService.AddLog(IsJb ? p.ItemID : p.TaskID, "撤销了工作计划(" + plan?.Measure + ")进展反馈(" + p.ProgressInfo + ")", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
